<template>
  <PageWrapper v-loading="loginLoading" loading-tip="登录中...">
    <BasicTable @register="registerTable">
      <template #form-channelCode="{ model, field }">
        <a-tree-select
          v-model:value="model[field]"
          :tree-data="channelTreeData"
          @change="treeSelectChange(model[field])"
          multiple
          allowClear
          :field-names="{
            label: 'channelName',
            value: 'channelCode',
            children: 'children'
          }"
          treeNodeFilterProp="channelName"
          placeholder="请选择渠道名称"
          :maxTagCount="3"
          showCheckedStrategy="SHOW_ALL"
          :dropdown-style="{ minWidth: '230px' }"
        ></a-tree-select>
      </template>
      <template #form-validTime="{ model, field }">
        <div class="flex-package">
          <a-select v-model:value="symbolSelect" placeholder="请选择" style="max-width: 100px">
            <a-select-option :value="item.value" v-for="item in symbolArr" :key="item.value">
              {{ item.label }}
            </a-select-option>
          </a-select>
          <a-form-item-rest>
            <a-input-number
              class="package-number"
              :precision="0"
              :controls="false"
              placeholder="请输入剩余天数"
              v-model:value="remainingDays"
              :min="0"
              :max="99999999"
            />
          </a-form-item-rest>
        </div>
      </template>

      <template #tableTitle>
        <a-space :size="12">
          <a-button type="primary" v-auth="permissionCodeMap.companyExport" @click="Export" :loading="exportLoading"
            >导出</a-button
          >
        </a-space>
      </template>

      <template #bodyCell="{ column, record, text }">
        <template v-if="column.dataIndex === 'validTime'">
          <div class="last-time">
            <template v-if="record.validTime !== '永久'">
              <span v-if="record.validTime === null">--</span>
              <template v-else>
                <span class="time-num"> {{ record.validTime }} </span><span>天</span>
              </template>
            </template>
            <span v-else>永久</span>
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'tryFlag'">
          <div class="try-out" v-if="record.tryFlag == 1">试用版</div>
          <div class="official" v-else-if="record.tryFlag == 2">正式版</div>
        </template>
        <template v-else-if="column.dataIndex === 'authStatus'">
          <span class="global-active-status" v-if="record.authStatus == 3"> 已开票 </span>
          <span class="global-certified-status" v-else-if="record.authStatus == 2"> 已认证 </span>
          <span class="global-wait-status" v-else-if="record.authStatus == 1"> 未认证 </span>
          <span class="global-stop-status" v-else-if="record.authStatus == 0"> 未知 </span>
        </template>
        <template v-if="column.dataIndex === 'multipleInvoicersCount'">
          <span
            :class="record.multipleInvoicersCount ? 'global-primary-text' : 'global-disabled-text'"
            @click="viewNum(record)"
          >
            {{ record.multipleInvoicersCount || 0 }}
          </span>
        </template>
        <template v-if="column.dataIndex === 'rpaType'">
          <span v-if="record.rpaType == 1">云端基础</span>
          <span v-else-if="record.rpaType == 2">云端VIP</span>
          <span v-else-if="record.rpaType == 3">本地基础</span>
          <span v-else>--</span>
        </template>
        <template v-else-if="column.dataIndex === 'createDate'">
          {{ record.createDate ? formatToDateTime(record.createDate) : '--' }}
        </template>
        <template v-else-if="column.dataIndex === 'lastOpenTime'">
          {{ record.lastOpenTime ? formatToDateTime(record.lastOpenTime) : '--' }}
        </template>
        <template v-else-if="column.dataIndex === 'lastLoginTime'">
          {{ record.lastLoginTime ? formatToDateTime(record.lastLoginTime) : '--' }}
        </template>
        <template v-else-if="column.dataIndex === 'orgStatus'">
          <span class="global-active-status" v-if="record.orgStatus == 0"> 正常 </span>
          <span class="global-error-status" v-else-if="record.orgStatus == 1"> 停用 </span>
        </template>
        <template v-else-if="column.dataIndex === 'operate'">
          <a-button
            v-if="record.orgStatus == 1"
            type="link"
            v-auth="permissionCodeMap.companyStatus"
            class="g-operate-btn"
            @click="openOrganization(operateActionTypeMap.ENABLE, record.taxesNumber, record)"
            >启用</a-button
          >
          <a-button
            v-else-if="record.orgStatus == 0"
            type="link"
            v-auth="permissionCodeMap.companyStatus"
            class="g-operate-btn"
            @click="openOrganization(operateActionTypeMap.UNABLE, record.taxesNumber, record)"
            >停用</a-button
          >
          <template v-if="record.rpaType == 1 || record.rpaType == 3">
            <a-button type="link" @click="openEdit(record)" v-auth="permissionCodeMap.companyEdit" class="g-operate-btn"
              >编辑</a-button
            >
          </template>
          <template v-else>
            <a-button type="link" v-auth="permissionCodeMap.companyEdit" class="g-operate-btn global-disabled-text">
              编辑
            </a-button>
          </template>
        </template>
      </template>
    </BasicTable>
    <TerminalNum @register="TerminalNumRegister" />
    <TerminalEdit @register="terminalEditRegister" @operateSuccess="reload" />
  </PageWrapper>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, unref, watch, nextTick, onMounted } from 'vue'
import PageWrapper from '@/components/PageWrapper/index.vue'
import { BasicTable, useTable } from '@/components/Table'
import { getSearchFormConfig, getCompanyBasicColums } from './dataSource'
import { userStore } from '@/store/modules/user'
import { permissionCodeMap } from '@/utils/permissionCodeMap'
import { operateActionType, operateTxtType, constantMap } from '@/types/enum'
import { downExcel } from '@/utils/axios/request'
import { message } from 'ant-design-vue'
import { formatToDateTime } from '@/utils/dateUtil'
import TerminalNum from './components/TerminalNum.vue'
import TerminalEdit from './components/TerminalEdit.vue'
import { transformToTree, createChannelTree } from '@/utils'
import { symbolArr, symbolDefault } from '@/utils/constantMap'
import api from '@/api'
import { useRouter } from 'vue-router'
import { any } from 'vue-types'
import { useDrawer } from '@/components/Drawer'
import { useModal } from '@/components/Modal'

const { companyList, switchCompany, queryChannelList } = api

const operateActionTypeMap = operateActionType
const loginLoading = ref(false)
const exportLoading = ref(false)

const channelTreeData = ref<any>([])
const seclectedChannel = ref<any>([])

// 套餐剩余时间
const symbolSelect = ref(symbolDefault)
const remainingDays = ref(null)

onMounted(async () => {
  const res = await queryChannelList()
  channelTreeData.value = transformToTree(res.result)
  console.log(res.result, channelTreeData.value)
})
const treeSelectChange = (data: any) => {
  console.log('测试数据======>', data)
  seclectedChannel.value = data
}

const [TerminalNumRegister, { openDrawer: TerminalNumDrawer }] = useDrawer()
const [terminalEditRegister, { openModal: editOpenModal }] = useModal()

const [registerTable, { reload, setPagination, getForm }] = useTable({
  api: companyList,
  columns: getCompanyBasicColums(),
  useSearchForm: true,
  beforeFetch: beforeParamsFetch,
  showIndexColumn: true,
  formConfig: { ...getSearchFormConfig(), resetFunc },
  indexColumnProps: {
    fixed: 'left'
  },
  rowKey: 'tenantId',
  scroll: { y: constantMap.tableYHeight, x: constantMap.tableXWidth }
})
async function resetFunc() {
  console.info('重置')
  symbolSelect.value = symbolDefault
  remainingDays.value = null
}
function beforeParamsFetch(params: any) {
  const { field, order, page, channelCode, ...rest } = params
  let asc
  let column
  let orders
  if (field) {
    asc = order === 'descend' ? false : true
    column = field
    orders = [
      {
        asc,
        column
      }
    ]
  }
  const { getFieldsValue } = getForm()
  const formData = getFieldsValue()
  const formChannel = formData.channelCode
  let channelCodeSet
  if (seclectedChannel.value.length > 0 && formChannel) {
    channelCodeSet = seclectedChannel.value
  }

  let paramsData = {
    ...rest,
    channelCodeSet,
    validTime: remainingDays.value || remainingDays.value == 0 ? remainingDays.value : undefined,
    validTimeCompare: remainingDays.value || remainingDays.value == 0 ? symbolSelect.value : undefined,
    page: {
      orders,
      pageNo: page.pageNo || 1,
      pageSize: page.pageSize || 10
    }
  }
  return paramsData
}
// 导出
const Export = async () => {
  const { getFieldsValue } = getForm()
  const formData = getFieldsValue()
  const { channelCode, ...rest } = formData
  exportLoading.value = true
  let channelCodeSet
  if (channelCode) {
    channelCodeSet = seclectedChannel.value
  }
  try {
    let res = await downExcel(
      '/api/tenant/manager/enterprise/export',
      {
        ...rest,
        validTime: remainingDays.value || remainingDays.value == 0 ? remainingDays.value : undefined,
        validTimeCompare: remainingDays.value || remainingDays.value == 0 ? symbolSelect.value : undefined,
        channelCodeSet
      },
      '导出数据'
    )
    exportLoading.value = false
    message.success('导出成功')
  } catch (error) {
    exportLoading.value = false
  }
}
// 查看数量
const viewNum = (record: any) => {
  if (record.multipleInvoicersCount) {
    TerminalNumDrawer(true, {
      record
    })
  }
}
// 启用/停用
const openOrganization = (type: any, companyTaxNo?: string, record?: any) => {
  switchCompany({
    orgStatus: record.orgStatus === 0 ? 1 : 0,
    tenant: record.tenantId
  })
    .then((result: any) => {
      const msg = type === operateActionType.UNABLE ? '停用' : '启用'
      if (result.code == 200) {
        message.success(`${msg}成功`)
        reload()
      } else {
        message.error(result.message || `${msg}失败`)
      }
    })
    .catch((err: any) => {})
}

// 编辑类型
const openEdit = (record: any) => {
  editOpenModal(true, record)
}
</script>

<style lang="less" scoped>
:deep(.ant-table-wrapper) {
  overflow-x: hidden;
}
.popupClass {
  width: 200px !important;
}
:deep(.ant-table-column-sorters) {
  justify-content: flex-start;
  .ant-table-column-title {
    flex: none;
  }
  .ant-table-column-sorter {
    margin-left: 8px;
  }
}
.time-num {
  color: @primary-color;
}
.try-out {
  text-align: center;
  width: 52px;
  height: 22px;
  line-height: 22px;
  background: #fef7e8;
  border-radius: 2px;
  border: 1px solid #f7d086;
  color: #d7802e;
  font-size: 12px;
  font-weight: 500;
}
.flex-package {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .package-number {
    flex: 1;
    margin-left: 8px;
  }
}
.official {
  text-align: center;
  width: 52px;
  height: 22px;
  line-height: 22px;
  background: #ebfeec;
  border-radius: 2px;
  border: 1px solid #9defaa;
  color: #4aa353;
  font-size: 12px;
  font-weight: 500;
}
</style>
